package oss

import (
	"context"
	"time"

	"github.com/minio/minio-go/v7"
)

type MinioClient struct {
	minio *minio.Client
}

func (mc *MinioClient) NewBucket(name string, region string, locking bool) (BucketManager, error) {
	if exists, err := mc.minio.BucketExists(context.Background(), name); err != nil {
		return nil, err
	} else if !exists {
		if err := mc.minio.MakeBucket(context.Background(), name,
			minio.MakeBucketOptions{
				Region:        region,
				ObjectLocking: locking,
			}); err != nil {
			return nil, err
		}
	}

	return &MinioBucket{
		client: mc.minio,
		name:   name,
	}, nil
}

func (mc *MinioClient) RemoveBucket(name string) error {
	return mc.minio.RemoveBucket(context.Background(), name)
}

func (mc *MinioClient) PresignedPutObjectURL(bucketName string, objectKey string, expireTime time.Duration) (string, error) {
	bucket, err := mc.NewBucket(bucketName, "", false)

	if err != nil {
		return "", err
	}

	url, err := bucket.PresignedPutObject(context.TODO(), objectKey, expireTime)

	if err != nil {
		return "", err
	}

	return url.String(), nil
}
